package httpserver

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
	"net/http"
)

//type query struct {
//	blocknum string `json: block_num`
//	blockid  string `json: block_id`
//}

var eser *elastic.Client

func RunHttpServer(bindAddress string, esClient *elastic.Client) {
	r := gin.Default()

	eser = esClient

	r.GET("/v1/chain/get_block", getBlock)
	r.Run(bindAddress)
}

func getBlock(ctx *gin.Context) {
	blockNum := ctx.DefaultQuery("block_num", "")
	blockId := ctx.DefaultQuery("block_id", "")

	if len(blockNum) != 0 {
		data, err := eser.Get().Index("chainblock").Id(blockNum).Do(context.Background())
		if err != nil {
			ctx.String(http.StatusInternalServerError, "%s", err.Error())
			return
		}
		json, err2 := data.Source.MarshalJSON()
		if err2 != nil {
			ctx.String(http.StatusInternalServerError, "%s", err2.Error())
			return
		}
		ctx.String(http.StatusOK, "%s", json)
	} else if len(blockId) != 0 {
		q := elastic.NewTermQuery("block_id", blockId)
		res, err := eser.Search().Index("chainblock").Query(q).Pretty(false).Do(context.Background())
		if err != nil {
			ctx.String(http.StatusInternalServerError, "%s", err.Error())
			return
		}
		if len(res.Hits.Hits) > 0 {
			for _, item := range res.Hits.Hits {
				ctx.String(http.StatusOK, "%s", string(item.Source))
			}
		} else {
			ctx.String(http.StatusNotFound, "%s", "NOT FOUND")
		}
	} else {
		ctx.String(http.StatusNotFound, "%s", "NOT FOUND")
	}
}
